import React, { useEffect } from 'react';
import { Table, Button, Space, Tag, Popconfirm, message, Input, Select, Card } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react-lite';
import { flowPathStore } from './store/flowpathStore';
import { FlowPath, FlowPathStatus } from './store/flowpathTypes';
import { useNavigate } from 'react-router-dom';

const { Search } = Input;
const { Option } = Select;

const FlowPathList: React.FC = observer(() => {
  const navigate = useNavigate();

  useEffect(() => {
    flowPathStore.fetchFlowPaths();
  }, []);

  const columns = [
    {
      title: '工作流名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: FlowPath) => (
        <a onClick={() => navigate(`/backhub/flowpath/detail/${record.id}`)}>{text}</a>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: FlowPathStatus) => {
        const statusMap = {
          [FlowPathStatus.DRAFT]: { color: 'default', text: '草稿' },
          [FlowPathStatus.PUBLISHED]: { color: 'success', text: '已发布' },
          [FlowPathStatus.ARCHIVED]: { color: 'warning', text: '已归档' },
          [FlowPathStatus.DISABLED]: { color: 'error', text: '已禁用' },
        };
        const { color, text } = statusMap[status];
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '节点数量',
      dataIndex: 'nodes',
      key: 'nodes',
      render: (nodes: FlowPath['nodes']) => nodes.length,
    },
    {
      title: '执行次数',
      dataIndex: 'executionCount',
      key: 'executionCount',
    },
    {
      title: '成功率',
      dataIndex: 'successCount',
      key: 'successCount',
      render: (successCount: number, record: FlowPath) => {
        const rate = record.executionCount > 0 
          ? ((successCount / record.executionCount) * 100).toFixed(2) 
          : '0.00';
        return `${rate}%`;
      },
    },
    {
      title: '平均执行时间',
      dataIndex: 'averageExecutionTime',
      key: 'averageExecutionTime',
      render: (time: number) => `${time}ms`,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: FlowPath) => (
        <Space size="middle">
          <Button type="link" onClick={() => flowPathStore.showEditModal(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => navigate(`/backhub/flowpath/execute/${record.id}`)}>
            执行
          </Button>
          <Button type="link" onClick={() => navigate(`/backhub/flowpath/statistics/${record.id}`)}>
            统计
          </Button>
          <Popconfirm
            title="确定要删除这个工作流吗？"
            onConfirm={() => {
              flowPathStore.deleteFlowPath(record.id);
              message.success('删除成功');
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Search
              placeholder="搜索工作流名称"
              allowClear
              style={{ width: 200 }}
              onSearch={(value) => {
                // TODO: 实现搜索功能
                console.log('搜索:', value);
              }}
            />
            <Select
              placeholder="状态筛选"
              style={{ width: 120 }}
              allowClear
              onChange={(value) => {
                // TODO: 实现状态筛选
                console.log('状态:', value);
              }}
            >
              {Object.values(FlowPathStatus).map(status => (
                <Option key={status} value={status}>
                  {status}
                </Option>
              ))}
            </Select>
          </Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => flowPathStore.showCreateModal()}
          >
            创建工作流
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={flowPathStore.flowPaths}
          rowKey="id"
          loading={flowPathStore.loading}
          locale={{ emptyText: '暂无数据' }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </Card>
    </div>
  );
});

export default FlowPathList;